import axios from 'axios'
import { Toast } from 'vant'
import { API_CONFIG } from '../config'

const http = axios.create({ 
  baseURL: API_CONFIG.BASE_URL,
  timeout: API_CONFIG.TIMEOUT
})

http.interceptors.request.use((config) => {
  // 启用请求日志
  if (API_CONFIG.ENABLE_LOG) {
    console.log(`🚀 API请求: ${config.method?.toUpperCase()} ${config.url}`, config.data || config.params)
  }
  
  // pass through existing trace id if present
  const existing = (window as any).traceId
  if (existing) {
    (config.headers as any)['X-Trace-Id'] = existing
  }
  return config
})

http.interceptors.response.use(
  (resp) => {
    // 启用响应日志
    if (API_CONFIG.ENABLE_LOG) {
      console.log(`✅ API响应: ${resp.config.method?.toUpperCase()} ${resp.config.url}`, resp.data)
    }
    
    const tid = resp.headers['x-trace-id']
    if (tid) (window as any).traceId = tid
    return resp
  },
  (err) => {
    // 启用错误日志
    if (API_CONFIG.ENABLE_LOG) {
      console.error(`❌ API错误: ${err.config?.method?.toUpperCase()} ${err.config?.url}`, err)
    }
    
    const resp = err?.response
    const tid = resp?.headers?.['x-trace-id']
    if (tid) (window as any).traceId = tid
    
    // 根据错误类型显示不同的错误信息
    let errorMessage = API_CONFIG.ERROR_MESSAGES.UNKNOWN_ERROR
    if (err.code === 'ECONNABORTED') {
      errorMessage = API_CONFIG.ERROR_MESSAGES.TIMEOUT_ERROR
    } else if (!resp) {
      errorMessage = API_CONFIG.ERROR_MESSAGES.NETWORK_ERROR
    } else if (resp.status >= 500) {
      errorMessage = API_CONFIG.ERROR_MESSAGES.SERVER_ERROR
    } else {
      errorMessage = resp?.data?.error || err?.message || '请求失败'
    }
    
    Toast.fail(errorMessage)
    return Promise.reject(err)
  }
)

export default http
